package com.wjk.kylin.mall.member.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.wjk.kylin.mall.common.core.dto.base.BaseOutDTO;
import com.wjk.kylin.mall.common.core.exception.BaseError;
import com.wjk.kylin.mall.common.web.filter.WrappedHttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 被调用方。降级处理
 * 没有配资源，默认Block异常处理（只能是Block异常）
 */
@Slf4j
@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value());

        BaseOutDTO dto = BaseOutDTO.error();

        if (e instanceof FlowException) {
            log.error("FlowException 普通服务限流，资源信息：{}", JSON.toJSONString(e.getRule()));
            httpServletResponse.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
            dto = BaseOutDTO.error(BaseError.REQ_FLOW_ERR);
        } else if (e instanceof DegradeException) {
            log.error("DegradeException 普通服务降级，资源信息：{}", JSON.toJSONString(e.getRule()));
            dto = BaseOutDTO.error(BaseError.REQ_DEGRADE_ERR);
        } else if (e instanceof ParamFlowException) {
            ParamFlowException ex = (ParamFlowException) e;
            log.error("ParamFlowException 参数热点限流，资源名={}，参数={}，资源信息={}", ex.getResourceName(), ex.getLimitParam(), JSON.toJSONString(ex.getRule()));
            dto = BaseOutDTO.error(BaseError.REQ_PARAM_FLOW_ERR);
        } else if (e instanceof AuthorityException) {
            log.error("AuthorityException 授权规则，资源信息：{}", JSON.toJSONString(e.getRule()));
            dto = BaseOutDTO.error(BaseError.REQ_AUTHORITY_ERR);
        } else if (e instanceof SystemBlockException) {
            SystemBlockException systemBlockException = (SystemBlockException) e;
            log.error("SystemBlockException，资源名：{}，资源类型：{}", systemBlockException.getResourceName(), systemBlockException.getRuleLimitApp());
            dto = BaseOutDTO.error(BaseError.REQ_SYSTEM_BLOCK_ERR);
        } else {
            log.error("BlockException 未知异常，异常信息：{}", e.getMessage());
        }

        String result = JSON.toJSONString(dto);
        log.error("BlockException return json:{}", result);

        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");
//        httpServletResponse.getWriter().write(result);//会乱码
        httpServletResponse.getOutputStream().write(result.getBytes());

        //将数据保存到buffer中
        ((WrappedHttpServletResponse) httpServletResponse).flushToDest();
    }
}
